import os
import time

from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.db.models import Q
from django.views.generic.base import View
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView
from rest_framework import viewsets
from apps.users.util import info, JwtToken
# Create your views here.
import requests
from apps.users.models import WeChatUser
from apps.users.auth import LoginAuth
from .models import *
from .forms import *
from tree.settings import SERVER_IP


def GetUserUID(request):
    l = LoginAuth()
    userUID = l.authenticate(request)
    user = WeChatUser.objects.get(uuid=userUID)
    # 获取用户是否被拉入黑名单
    if user.id_delete==True:
        return info(status=201, message="用户已被拉入黑名单")
    return userUID
def GetUserID(request):
    l = LoginAuth()
    userUID = l.authenticate(request)
    user = WeChatUser.objects.get(uuid=userUID)
    # 获取用户是否被拉入黑名单
    if user.id_delete==True:
        return info(status=201, message="用户已被拉入黑名单")
    return user.id

# 话题
class TopicView(APIView):

    # 新建
    def post(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")

        user = WeChatUser.objects.get(uuid=userID)
        try:
            topic = Topic()
            topic.tag = TopicTag.objects.get(tag="综合分区")
            topic.author = user
            topic.save()

            return info(status=200, message="打开成功",data={
                "textId": topic.id
            })
        except:
            return info(status=0, message="服务繁忙")

    # 更新
    def put(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")


        try:
            topic = Topic.objects.get(id=data.get('textId'))
            topic.text = data.get('context')
            topic.title = data.get('title')
            if data.get('tag'):
                topic.tag_id = data.get('tag')
            topic.is_show = True
            topic.save()
            return info(status=200, message="发布成功")
        except:
            return info(status=0, message="服务繁忙")

    # 删除
    def delete(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")

        try:
            Topic.objects.get(id=data.get('textId')).delete()

            return info(status=200, message="删除成功")
        except:
            return info(status=0, message="服务繁忙")

    # 获取当前话题详细
    def get(self, request):
        data = request.GET
        # try:
        #     userID = GetUserUID(request)
        # except:
        #     return info(status=0, message="token失效或错误")
        try:
            dataList = []
            imgListJson=[]

            nowLikeJson = False
            topic = Topic.objects.get(id=data.get('topicId'))
            tag = topic.tag.tag
            author = model_to_dict(topic.author)
            # 返回是否点赞
            if data.get('userId'):
                nowLike = Like.objects.filter(topic_id=topic.id, user_id=data.get('userId'))
                if nowLike:
                    nowLikeJson = True
            # 取出话题对应的图片
            imgList = TopicImg.objects.filter(topic=topic)
            if imgList:
                for img in imgList:
                    image = SERVER_IP + os.path.join("media/", str(img.image))
                    imgLi = {
                        "id": img.id,
                        "imageUrl": image,
                        "topicId": img.topic_id
                    }
                    imgListJson.append(imgLi)
            topic = model_to_dict(topic)
            dataList.append(topic)
            dataList.append(imgListJson)
            dataList.append(author)
            dataList.append({"nowlike":nowLikeJson,
                             "tag":tag})
            # print(time.strftime('%Y-%m-%d %H:%M:%S', res['add_time']))
            topic['add_time'] = topic['add_time'].strftime("%Y-%m-%d")
            return info(status=200, message="获取详细成功", data={
                'data': dataList
            })
        except:
            return info(status=0, message="服务繁忙")

# 返回所有话题
class TopicAllView(APIView):

    # 返回所有话题
    def get(self, request):
        data = request.GET
        # try:
        #     userID = GetUserUID(request)
        # except:
        #     return info(status=0, message="token失效或错误")
        dataJson = []
        # try:
        # 如果有tagid那么就取对应标签的值
        topicList = Topic.objects.filter(is_show=True)

        if data.get('tagid'):
            topicList = topicList.filter(tag_id=data.get('tagid'),is_show=True)
        else:
            topicList = topicList.filter(~Q(tag_id=1),is_show=True)
        if data.get('selfid'):
            topicList = topicList.filter(author_id=data.get('selfid'),is_show=True).order_by('-add_time')
        if data.get('search'):
            #加__icontains使用模糊搜索
            topicList = topicList.filter(Q(title__icontains=data.get('search')) | Q(text__icontains=data.get('search'))|
                                         Q(author__username__icontains=data.get('search'))
                                         ,is_show=True).order_by('-add_time')

        order = data.get('order')
        # 排序
        if order=="hot":
            topicList = topicList.order_by('-likenum')
        elif order=="time":
            topicList = topicList.order_by('-add_time')

        # 遍历格式化话题
        for inx,res in enumerate(topicList):
            topicListJson = []
            imgListJson = []
            tag=res.tag.tag
            nowLikeJson = False
            # 返回作者数据
            author = res.author
            author = model_to_dict(author)
            # 返回是否点赞
            if data.get('userId'):
                nowLike = Like.objects.filter(topic_id=res.id, user_id=data.get('userId'))
                if nowLike:
                    nowLikeJson = True

            # 取出话题对应的图片
            imgList = TopicImg.objects.filter(topic=res)
            if imgList:
                for img in imgList:
                    image =SERVER_IP+os.path.join("media/", str(img.image))
                    imgLi = {
                        "id":img.id,
                        "imageUrl":image,
                        "topicId":img.topic_id
                    }
                    imgListJson.append(imgLi)

            res = model_to_dict(res)
            # print(time.strftime('%Y-%m-%d %H:%M:%S', res['add_time']))
            res['add_time'] = res['add_time'].strftime("%Y-%m-%d")
            topicListJson.append(imgListJson)
            topicListJson.append(author)
            topicListJson.append(res)
            topicListJson.append({
                "nowlike":nowLikeJson,
                "tag":tag
                                  })
            dataJson.append(topicListJson)
        return info(status=200, message="获取成功",data={
            "topicList":dataJson
        })
        # except:
        #     return info(status=0, message="服务繁忙")

# 话题图片上传
class TopicImgView(APIView):
    def post(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")
        try:
            topic = Topic.objects.get(id=data.get("topicId"))
            # if topic.tag.tag=="树洞":
            #     return info(status=0, message="树洞不能有图片")
            topicImg = TopicImg()
            topicImg.topic = topic
            topicImg.save()
            image_form = UploadImageForm(request.POST, request.FILES,instance=topicImg)  # 指明实例
            if image_form.is_valid():
                image_form.save()
                return info(status=200, message="打开成功", data={
                    "imageId": topicImg.id
                })
            return info(status=0, message="上传失败")
        except:
            return info(status=0, message="服务繁忙")

    # 删除
    def delete(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")

        try:
            topicimg = TopicImg.objects.get(id=data.get('imgId'))
            path = os.path.join("media/",str(topicimg.image))
            topicimg.delete()
            os.remove(path)
            return info(status=200, message="删除成功")
        except:
            return info(status=0, message="服务繁忙")

# 点赞
class LikeView(APIView):
    # 给话题点赞
    def post(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")
        try:
            nowLike = Like.objects.filter(topic_id=data.get('topicId'),user_id=data.get('userId'))
            if nowLike:
                nowLike.delete()
                topic = Topic.objects.get(id=data.get('topicId'))
                topic.likenum = topic.likenum - 1
                topic.save()
                return info(status=200, message="取消成功",data={
                    "nowLike": False,
                    "likenum": topic.likenum
                })
            like = Like()
            like.topic_id = data.get('topicId')
            like.user_id = data.get('userId')
            # user = WeChatUser.objects.get(uuid=userID)
            # like.user_id = user.id
            like.save()
            topic = Topic.objects.get(id=data.get('topicId'))
            topic.likenum = topic.likenum+1
            topic.save()
            return info(status=200, message="点赞成功",data={
                    "nowLike": True,
                    "likenum": topic.likenum
                })
        except:
            return info(status=0, message="服务繁忙")
    # 获取所有自己点赞过的话题
    def get(self, request):
        data = request.GET
        # try:
        #     userID = GetUserUID(request)
        # except:
        #     return info(status=0, message="token失效或错误")
        dateList =[]

        selfLike = Like.objects.filter(user_id=data.get('userId'))
        if selfLike:
            for like in selfLike:
                topic = like.topic
                topicList = model_to_dict(like.topic)
                likeList = model_to_dict(like)
                likeList['add_time'] = likeList['add_time'].strftime("%Y-%m-%d")
                # 取出话题对应的图片
                imgList = TopicImg.objects.filter(topic_id=topic.id)
                imgListJson = []
                if imgList:

                    for img in imgList:
                        image = SERVER_IP + os.path.join("media/", str(img.image))
                        imgList = {
                            "id": img.id,
                            "imageUrl": image,
                            "topicId": img.topic_id
                        }
                        imgListJson.append(imgList)
                data = {
                    "topic":topicList,
                    "like":likeList,
                    "img":imgListJson
                }
                dateList.append(data)
        return info(status=200, message="获取成功", data={
            "data": dateList
        })

# 评论
class CommentView(APIView):
    # 添加话题评论
    def post(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")
        try:
            comment = TopicComments()
            comment.topic_id = data.get('topicId')
            comment.user_id = data.get('userId')
            comment.comments = data.get('comment')
            # user = WeChatUser.objects.get(uuid=userID)
            # like.user_id = user.id
            comment.save()
            topic = Topic.objects.get(id=data.get('topicId'))
            topic.commentnum = topic.commentnum+1
            topic.save()
            return info(status=200, message="评论成功")
        except:
            return info(status=0, message="服务繁忙")
    # 删除评论
    def delete(self, request):
        data = request.data
        try:
            userID = GetUserUID(request)
        except:
            return info(status=0, message="token失效或错误")
        try:
            comment = TopicComments.objects.get(id=data.get('commentId'))
            comment.delete()
            # user = WeChatUser.objects.get(uuid=userID)
            # like.user_id = user.id
            topic = Topic.objects.get(id=comment.topic_id)
            topic.commentnum = topic.commentnum - 1
            topic.save()
            return info(status=200, message="删除评论成功")
        except:
            return info(status=0, message="服务繁忙")
    # 获取所有评论
    def get(self, request):
        data = request.GET
        # try:
        #     userID = GetUserUID(request)
        # except:
        #     return info(status=0, message="token失效或错误")
        try:
            dataList = []
            commentList = TopicComments.objects.filter(topic_id=data.get('topicId'))
            for comment in commentList:
                user = comment.user
                comment = model_to_dict(comment)
                user = model_to_dict(user)
                comment['add_time'] = comment['add_time'].strftime("%Y-%m-%d")
                comment = {
                    'comment':comment,
                    'user':user,
                }
                dataList.append(comment)
            return info(status=200, message="获取评论成功",data={
                'data': dataList
            })
        except:
            return info(status=0, message="服务繁忙")

# 分类
class TagView(APIView):
    # 获取所有标签
    def get(self, request):
        data = request.GET
        # try:
        #     userID = GetUserUID(request)
        # except:
        #     return info(status=0, message="token失效或错误")
        try:
            dataList = []
            TagList = TopicTag.objects.all()
            for tag in TagList:
                topicNums = tag.message_nums()
                tag = model_to_dict(tag)
                tag = {
                    'topicNums': topicNums,
                    'tag': tag,
                }
                dataList.append(tag)
            return info(status=200, message="获取标签成功", data={
                'data': dataList
            })
        except:
            return info(status=0, message="服务繁忙")

# 用户消息
class MessageView(APIView):
    # 获取所有消息
    def get(self, request):
        data = request.GET
        try:
            userID = GetUserID(request)
        except:
            return info(status=0, message="token失效或错误")
        # try:
        dataList = []
        read = True
        if data.get("type")=="like":
            List = Like.objects.filter(topic__author_id=userID).order_by('-add_time')
        else:
            List = TopicComments.objects.filter(topic__author_id=userID).order_by('-add_time')
        # List = TopicTag.objects.all()
        for res in List:
            if res.user_id == userID:
                continue
            res_dict = model_to_dict(res)
            topic = Topic.objects.get(id=res_dict["topic"])
            topic = model_to_dict(topic)
            user = WeChatUser.objects.get(id=res_dict["user"])
            user = model_to_dict(user)
            datas = {
                'topic': topic,
                'message': res_dict,
                'user':user
            }
            dataList.append(datas)
            if res_dict["is_read"] == False and data.get("read") == "is":
                res.is_read = True
                res.save()
            if res_dict["is_read"] == False and read==True:
                read = False
        return info(status=200, message="获取消息成功", data={
            'data': dataList,
            'read': read
            })
        # except:
        #     return info(status=0, message="服务繁忙")

